package net.http;

import java.io.IOException;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.Assert;

public class HttpClientHelper extends HttpClient{
	static final Logger logger = LogManager.getLogger(HttpClientHelper.class.getName());

	public HttpClientHelper() {
		getHttpConnectionManager().getParams()
				.setConnectionTimeout(5000);
	}
	public String queryHttpServer(HttpMethod method) {
		// create a method object
		method.setFollowRedirects(true);
		try {
			executeMethod(method);
		} catch (HttpException e) {
			logger.error("", e);
			Assert.fail();
		} catch (IOException e) {
			logger.error("", e);
			Assert.fail();
		}
		String responseBody = null;
		try {
			responseBody = method.getResponseBodyAsString();
		} catch (IOException e) {
			logger.error("", e);
			Assert.fail();
		}
		// write out the response headers
		logger.debug("*** Response ***");
		logger.debug(String.format("Status Line: %s", method.getStatusLine()));
		Header[] responseHeaders = method.getResponseHeaders();
		for (int i = 0; i < responseHeaders.length; i++) {
			logger.debug(responseHeaders[i]);
		}
		// write out the response body
		logger.debug("*** Response Body ***");
		logger.debug(responseBody);
		return responseBody;
	}	
}
